package com.seeyon.apps.taxFund.event;


import com.fasterxml.jackson.core.type.TypeReference;
import com.seeyon.apps.commonExt.util.CommonRestUtil;
import com.seeyon.apps.taxFund.api.LQAPIRequest;
import com.seeyon.apps.taxFund.api.ShuiJinEnum;
import com.seeyon.apps.util.CAP4FormKit;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import com.seeyon.ctp.workflow.util.WorkflowEventConstants.WorkflowEventType;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class FaPiaoChaYanEvent extends AbstractWorkflowEvent {

    private static final Logger log = LoggerFactory.getLogger(FaPiaoChaYanEvent.class);

    private final CAP4FormManager cap4FormManager;

    public FaPiaoChaYanEvent(CAP4FormManager cap4FormManager) {
        this.cap4FormManager = cap4FormManager;
    }


    @Override
    public ApplicationCategoryEnum getAppName() {
        // TODO 自动生成的方法存根
        return ApplicationCategoryEnum.form;
    }

    @Override
    public WorkflowEventType getType() {
        // TODO 自动生成的方法存根
        return WorkflowEventType.Ext;
    }

    @Override
    public String getId() {
        return "faPiaoChaYanEvent";
    }

    @Override
    public String getLabel() {
        return "乐企发票查验";
    }

    /*
     * 流程发起前事件
     *
     */
    @Override
    public synchronized WorkflowEventResult onBeforeStart(WorkflowEventData data) {
        log.info("=========================进入-乐企发票查验-onBeforeStart=============================");


        WorkflowEventResult res = null;
        try {
            res = new WorkflowEventResult();
            Map<String, Object> map = data.getBusinessData();
            //获取表单的数据
            FormDataMasterBean master = (FormDataMasterBean) map.get("formDataBean");
            Long formId = master.getFormTable().getFormId();
            FormBean formBean = cap4FormManager.getForm(formId, true);

            FormTableBean dtlTableBean = CAP4FormKit.getSubTableBeanByDisplay(formBean, "票据信息明细表");
            Assert.notNull(dtlTableBean, "【{}】不存在", "票据信息明细表");

            for (FormDataSubBean subData : master.getSubData(dtlTableBean.getTableName())) {
                String fplx = CAP4FormKit.getFieldValue(subData, "发票类型", String.class);
                String fpdm = CAP4FormKit.getFieldValue(subData, "发票代码", String.class);
                String fphm = CAP4FormKit.getFieldValue(subData, "发票号码", String.class);
                Date kprq = CAP4FormKit.getFieldValue(subData, "开票日期", Date.class);
                String nsrsbh = CAP4FormKit.getFieldValue(subData, "纳税人识别号", String.class);

                Map<String, Object> apiParams = new HashMap<>();
                // 发票类型 必填
                apiParams.put("fplx", fplx);
                // 发票代码
                apiParams.put("fpdm", fpdm);
                // 发票号码 必填
                apiParams.put("fphm", fphm);
                // 开票日期 必填
                apiParams.put("kprq", DateUtil.format(kprq, "yyyy-MM-dd"));
                // 校验码
    //        apiParams.put("jym", master);
                // 开票金额
    //        apiParams.put("kpje", master);
                // 纳税人识别号 必填
                apiParams.put("nsrsbh", nsrsbh);
                LQAPIRequest lqapiRequest = new LQAPIRequest("BASE.CHECKINVOICE", apiParams);

                ResponseEntity<String> responseEntity = CommonRestUtil.post(ShuiJinEnum.INVOICE_VALID, null, lqapiRequest);
                String body = responseEntity.getBody();
                Map<String, Object> result = JSONUtil.parseJSONString(body, new TypeReference<Map<String, Object>>() {
                }.getType());
                Map<String, Object> returnInfo = MapUtil.get(result, "return_info", new cn.hutool.core.lang.TypeReference<Map<String, Object>>() {
                });
                String returnCode = MapUtil.getStr(returnInfo, "return_code");
                String return_message = MapUtil.getStr(returnInfo, "return_message");
                Assert.isTrue("0000".equals(returnCode), "税金-乐企发票查验异常【{}】", return_message);
            }
        } catch (Exception e) {
            res.setAlertMessage(StrUtil.format("【{}】异常【{}】", "税金-乐企发票查验", e.getMessage()));
        }
        log.info("=========================退出-乐企发票查验-onBeforeStart=============================");
        return res;
    }
}
